﻿//NorManager - OpenTTD Dedicated server manager
//Copyright (C) 2014 Tomáš Bosek

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Diagnostics;
using System.Text;
using System.IO;

namespace NorManager
{
    /// <summary>
    /// SessionWriter writes into process input stream.
    /// </summary>
    public class SessionWriter
    {
        private StreamWriter writer = null;

        /// <summary>
        /// Initializes SessionWriter.
        /// </summary>
        internal SessionWriter()
        {
            writer = Session.Instance.SessionProc.StandardInput;

            if (writer == null)
            {
                Logger.Instance.Log("Cannot write to this(NULL) stream!");
                return;
            }

            writer.AutoFlush = true;
        }

        /// <summary>
        /// Sends command into process input stream.
        /// </summary>
        /// <param name="command">Command to send.</param>
        public void Write(string command)
        {
            if (writer != null)
            {
                try
                {
                    writer.WriteLine(command);
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log("Exception during SessionWriter.Write method: "+ex.Message);
                }
            }
        }

        /// <summary>
        /// Closes writer stream.
        /// </summary>
        internal void CloseWriter()
        {
            if (writer != null)
            {
                writer.Dispose();
                writer = null;
            }
        }
    }
}
